/**
 * @file KHttp
 * @author zhangjie(769669896@qq.com)
 */
var KHttp = function($) {
    var timeout = 10000;

    /**
     *  消息提示
     *
     * @param {Object} response response
     */
    var alertMessage = function (response) {
        let method = response.config.method;
        let msg = '数据请求';
        //TODO 兼容新老版本框架的数据交互
        let status = response.data.status || response.data.resCode;
        let dataMsg = response.data.msg || response.data.errorMsg;
        if (method === 'get'
            && (status === '0000'
                // 人员培训取证资质重复
                || status === '0004'
                // 申请人资质重复
                || status === '1002')) {
            response.data.state = true;
            return;
        }
        else if (method === 'post') {
            msg = '你的信息提交';
        }
        else if (method === 'delete') {
            msg = '你的信息删除';
        }

        if (status === '0000') {
            response.data.state = true;
            KDatacom.alert({
                type: 'success',
                msg: dataMsg|| msg + '成功！'
            });
        }
        else {
            response.data.state = false;
            KDatacom.alert({
                type: 'warning',
                msg: dataMsg || msg + '失败！'
            });
        }
    };


    /**
     * 检查响应状态
     * @param response
     * @param disableAlert
     * @returns {*}
     */
    var checkStatus = function (response, disableAlert) {
        // loading
        // 如果http状态码正常，则直接返回数据
        if (response && (
            response.status === 200
            || response.status === 304
            || response.status === 400)) {

            if (disableAlert !== true) {
                alertMessage(response);
            }

            return response;
            // 如果不需要除了data之外的数据，可以直接 return response.data
        }

        // 异常状态下，把错误信息返回去
        return {
            status: -404,
            msg: '网络异常'
        };
    };

    /**
     * 检查错误信息
     *
     * @param {Object} res response
     * @return {Object} res response
     */
    var checkCode = function (res) {
        // 如果code异常(这里已经包括网络错误，服务器错误，后端抛出的错误)，可以弹出一个错误提示，告诉用户
        if (res.status === -404) {
            console.log(res.msg);
            KDatacom.alert({
                type: 'danger',
                msg: res.msg
            });
        }

        return res.data;
    };

    /**
     * 获取文件名称
     *
     * @param {Object} response response
     * @return {string} filename filename
     */
    var getFileName = function (response) {
        let fileUrl = response.config.url;
        let startIndex = fileUrl.lastIndexOf('/') + 1;
        let filename = fileUrl.substring(startIndex, fileUrl.length);
        let disposition = response.headers['Content-Disposition'];
        if (disposition && disposition.indexOf('attachment') !== -1) {
            let filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
            let matches = filenameRegex.exec(disposition);
            if (matches != null && matches[1]) {
                filename = matches[1].replace(/['"]/g, '');
            }
        }

        return filename;
    };

    /**
     * 下载文件
     *
     * @param {Object} response response
     * @param {Object} params file
     */
    var downloadFile = function(response, params) {
        if (!response.data) {
            return;
        }

        let url = window.URL.createObjectURL(new Blob([response.data]));
        let link = document.createElement('a');

        link.style.display = 'none';
        link.href = url;
        link.setAttribute('download', params.name || getFileName(response));

        document.body.appendChild(link);
        link.click();
    };

    /**
     * 初始化http模块
     * @param mainServer 主框架服务器地址
     * @param server  子服务器地址
     */
    var initHttp = function (mainServer, server) {
        var MAIN_SERVER_URL = mainServer || location.origin;
        var SERVER_URL = server || location.origin;

        if (!axios) {
            return;
        }

        axios.defaults.baseURL = SERVER_URL;
        axios.defaults.withCredentials = true;
        axios.interceptors.request.use(config => {
            let auth = JSON.stringify({
                pfToken: sessionStorage ? sessionStorage.getItem('token') : ''
            });

            config.headers.common = {
                Authorization: auth
            };

            return config;
        }, error => {
            return Promise.reject(error);
        });

        axios.interceptors.response.use(response => {
            if (response.data.status === '0005') {
                setTimeout(function () {
                    window.location.href = MAIN_SERVER_URL + '/login.htm';
                }, 3 * 1000)
            }

            return response;
        }, error => {
            return Promise.resolve(error.response);
        });
    };

    /**
     * 获取数据
     * @param url
     * @param params
     * @returns {*}
     */
    var getData = function(url, params) {
        for (let prop in params) {
            if (Array.isArray(params[prop])) {
                params[prop] = params[prop].toString();
            }
        }
        return axios({
            method: 'get',
            url,
            params, // get 请求时带的参数
            timeout: timeout,
            headers: {
                'X-Requested-With': 'XMLHttpRequest'
            }
        }).then(
            (response) => {
                return checkStatus(response);
            }
        ).then(
            (res) => {
                return checkCode(res);
            }
        );
    };

    /**
     * 提交数据
     * @param url
     * @param data
     */
    var postData = function(url, data) {
        return axios({
            method: 'post',
            url,
            data: JSON.stringify(data),
            timeout: timeout,
            headers: {
                'X-Requested-With': 'XMLHttpRequest',
                'dataType':'json',
                'Content-Type': 'application/json; charset=UTF-8'
            }
        }).then(
            (response) => {
                return checkStatus(response);
            }
        ).then(
            (res) => {
                return checkCode(res);
            }
        );
    };

    /**
     * 删除数据
     * @param url
     * @param params
     */
    var deleteData = function(url, params) {
        for (let prop in params) {
            if (Array.isArray(params[prop])) {
                params[prop] = params[prop].toString();
            }
        }
        return axios({
            method: 'delete',
            url,
            params, // delete 请求时带的参数
            timeout: timeout,
            headers: {
                'X-Requested-With': 'XMLHttpRequest',
                'Content-Type': 'application/json; charset=UTF-8'
            }
        }).then(
            (response) => {
                return checkStatus(response);
            }
        ).then(
            (res) => {
                return checkCode(res);
            }
        );
    };

    /**
     * 下载文件
     * @param url
     * @param params
     */
    var download = function(url, params) {
        axios({
            method: 'get',
            url: url,
            data: params,
            responseType: 'blob'
        }).then((response) => {
            downloadFile(response, params || {});
        });
    };

    /**
     * 加载html
     * @param url
     * @param params
     */
    var loadHtml = function(url, params) {
        var $container = $(this);
        if ($container.length === 0) {
            return;
        }

        for (let prop in params) {
            if (Array.isArray(params[prop])) {
                params[prop] = params[prop].toString();
            }
        }
        axios({
            method: 'get',
            url,
            params,
            timeout: timeout,
            responseType: 'text'
        }).then(
            (response) => {
                var res = checkStatus(response, true);
                if (res.status !== -404) {
                    $container.html(res.data);
                }
                return res;
            }
        ).then(
            (res) => {
                return checkCode(res);
            }
        );
    };

    $.fn.extend({
        loadHtml: loadHtml
    });

    return {
        init: initHttp,
        get: getData,
        post: postData,
        delete: deleteData,
        download: download
    }
}(jQuery);

// Class initialization on page load
jQuery(document).ready(function () {
    KHttp.init();
});

// Class definition
var KLib = function() {

    return {
        initMiniChart: function(src, data, color, border, fill, tooltip) {
            if (src.length == 0) {
                return;
            }

            // set default values
            fill = (typeof fill !== 'undefined') ? fill : false;
            tooltip = (typeof tooltip !== 'undefined') ? tooltip : false;

            var config = {
                type: 'line',
                data: {
                    labels: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October"],
                    datasets: [{
                        label: "",
                        borderColor: color,
                        borderWidth: border,
                        pointHoverRadius: 4,
                        pointHoverBorderWidth: 4,
                        pointBackgroundColor: Chart.helpers.color('#000000').alpha(0).rgbString(),
                        pointBorderColor: Chart.helpers.color('#000000').alpha(0).rgbString(),
                        pointHoverBackgroundColor: KApp.getStateColor('brand'),
                        pointHoverBorderColor: Chart.helpers.color('#000000').alpha(0.1).rgbString(),
                        fill: fill,
                        backgroundColor: color,
                        data: data,
                    }]
                },
                options: {
                    title: {
                        display: false,
                    },
                    tooltips: (tooltip ? {
                        enabled: true,
                        intersect: false,
                        mode: 'nearest',
                        bodySpacing: 5,
                        yPadding: 10,
                        xPadding: 10, 
                        caretPadding: 0,
                        displayColors: false,
                        backgroundColor: KApp.getStateColor('brand'),
                        titleFontColor: '#ffffff', 
                        cornerRadius: 4,
                        footerSpacing: 0,
                        titleSpacing: 0
                    } : false),
                    legend: {
                        display: false,
                        labels: {
                            usePointStyle: false
                        }
                    },
                    responsive: false,
                    maintainAspectRatio: true,
                    hover: {
                        mode: 'index'
                    },
                    scales: {
                        xAxes: [{
                            display: false,
                            gridLines: false,
                            scaleLabel: {
                                display: false,
                                labelString: 'Month'
                            }
                        }],
                        yAxes: [{
                            display: false,
                            gridLines: false,
                            scaleLabel: {
                                display: false,
                                labelString: 'Month'
                            }
                        }]
                    },

                    elements: {
                        line: {
                            tension: 0.5
                        },
                        point: {
                            radius: 2,
                            borderWidth: 4
                        },
                    },

                    layout: {
                        padding: {
                            left: 6,
                            right: 0,
                            top: 4,
                            bottom: 0
                        }
                    }
                }
            };

            var chart = new Chart(src, config);
        },

        initMediumChart: function(src, data, max, color, border) {
            if (!document.getElementById(src)) {
                return;
            }

            var border = border ? border : 2;

            // Main chart
            var ctx = document.getElementById(src).getContext("2d");

            var gradient = ctx.createLinearGradient(0, 0, 0, 100);
            gradient.addColorStop(0, Chart.helpers.color(color).alpha(0.3).rgbString());
            gradient.addColorStop(1, Chart.helpers.color(color).alpha(0).rgbString());

            var mainConfig = {
                type: 'line',
                data: {
                    labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October'],
                    datasets: [{
                        label: 'Orders',
                        borderColor: color,
                        borderWidth: border,
                        backgroundColor: gradient,
                        pointBackgroundColor: KApp.getStateColor('brand'),
                        data: data,
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    title: {
                        display: false,
                        text: 'Stacked Area'
                    },
                    tooltips: {
                        enabled: true,
                        intersect: false,
                        mode: 'nearest',
                        bodySpacing: 5,
                        yPadding: 10,
                        xPadding: 10, 
                        caretPadding: 0,
                        displayColors: false,
                        backgroundColor: KApp.getStateColor('brand'),
                        titleFontColor: '#ffffff', 
                        cornerRadius: 4,
                        footerSpacing: 0,
                        titleSpacing: 0
                    },
                    legend: {
                        display: false,
                        labels: {
                            usePointStyle: false
                        }
                    },
                    hover: {
                        mode: 'index'
                    },
                    scales: {
                        xAxes: [{
                            display: false,
                            scaleLabel: {
                                display: false,
                                labelString: 'Month'
                            },
                            ticks: {
                                display: false,
                                beginAtZero: true,
                            }
                        }],
                        yAxes: [{
                            display: false,
                            scaleLabel: {
                                display: false,
                                labelString: 'Value'
                            },
                            gridLines: {
                                color: '#eef2f9',
                                drawBorder: false,
                                offsetGridLines: true,
                                drawTicks: false
                            },
                            ticks: {
                                max: max,
                                display: false,
                                beginAtZero: true
                            }
                        }]
                    },
                    elements: {
                        point: {
                            radius: 0,
                            borderWidth: 0,
                            hoverRadius: 0,
                            hoverBorderWidth: 0
                        }
                    },
                    layout: {
                        padding: {
                            left: 0,
                            right: 0,
                            top: 0,
                            bottom: 0
                        }
                    }
                }
            };

            var chart = new Chart(ctx, mainConfig);

            // Update chart on window resize
            KUtil.addResizeHandler(function() {
                chart.update();
            });
        }
    };
}();
var KOffcanvasPanel = function() {
    var notificationPanel = KUtil.get('k_offcanvas_toolbar_notifications');
    var quickActionsPanel = KUtil.get('k_offcanvas_toolbar_quick_actions');
    var profilePanel = KUtil.get('k_offcanvas_toolbar_profile');
    var searchPanel = KUtil.get('k_offcanvas_toolbar_search');

    var initNotifications = function() {
        var head = KUtil.find(notificationPanel, '.k-offcanvas-panel__head');
        var body = KUtil.find(notificationPanel, '.k-offcanvas-panel__body');

        var offcanvas = new KOffcanvas(notificationPanel, {
            overlay: true,  
            baseClass: 'k-offcanvas-panel',
            closeBy: 'k_offcanvas_toolbar_notifications_close',
            toggleBy: 'k_offcanvas_toolbar_notifications_toggler_btn'
        }); 

        KUtil.scrollInit(body, {
            disableForMobile: true, 
            resetHeightOnDestroy: true, 
            handleWindowResize: true, 
            height: function() {
                var height = parseInt(KUtil.getViewPort().height);
               
                if (head) {
                    height = height - parseInt(KUtil.actualHeight(head));
                    height = height - parseInt(KUtil.css(head, 'marginBottom'));
                }
        
                height = height - parseInt(KUtil.css(notificationPanel, 'paddingTop'));
                height = height - parseInt(KUtil.css(notificationPanel, 'paddingBottom'));    

                return height;
            }
        });
    }

    var initQucikActions = function() {
        var head = KUtil.find(quickActionsPanel, '.k-offcanvas-panel__head');
        var body = KUtil.find(quickActionsPanel, '.k-offcanvas-panel__body');

        var offcanvas = new KOffcanvas(quickActionsPanel, {
            overlay: true,  
            baseClass: 'k-offcanvas-panel',
            closeBy: 'k_offcanvas_toolbar_quick_actions_close',
            toggleBy: 'k_offcanvas_toolbar_quick_actions_toggler_btn'
        }); 

        KUtil.scrollInit(body, {
            disableForMobile: true, 
            resetHeightOnDestroy: true, 
            handleWindowResize: true, 
            height: function() {
                var height = parseInt(KUtil.getViewPort().height);
               
                if (head) {
                    height = height - parseInt(KUtil.actualHeight(head));
                    height = height - parseInt(KUtil.css(head, 'marginBottom'));
                }
        
                height = height - parseInt(KUtil.css(quickActionsPanel, 'paddingTop'));
                height = height - parseInt(KUtil.css(quickActionsPanel, 'paddingBottom'));    

                return height;
            }
        });
    }

    var initProfile = function() {
        var head = KUtil.find(profilePanel, '.k-offcanvas-panel__head');
        var body = KUtil.find(profilePanel, '.k-offcanvas-panel__body');

        var offcanvas = new KOffcanvas(profilePanel, {
            overlay: true,  
            baseClass: 'k-offcanvas-panel',
            closeBy: 'k_offcanvas_toolbar_profile_close',
            toggleBy: 'k_offcanvas_toolbar_profile_toggler_btn'
        }); 

        KUtil.scrollInit(body, {
            disableForMobile: true, 
            resetHeightOnDestroy: true, 
            handleWindowResize: true, 
            height: function() {
                var height = parseInt(KUtil.getViewPort().height);
               
                if (head) {
                    height = height - parseInt(KUtil.actualHeight(head));
                    height = height - parseInt(KUtil.css(head, 'marginBottom'));
                }
        
                height = height - parseInt(KUtil.css(profilePanel, 'paddingTop'));
                height = height - parseInt(KUtil.css(profilePanel, 'paddingBottom'));    

                return height;
            }
        });
    }

    var initSearch = function() {
        var head = KUtil.find(searchPanel, '.k-offcanvas-panel__head');
        var body = KUtil.find(searchPanel, '.k-offcanvas-panel__body');
        
        var offcanvas = new KOffcanvas(searchPanel, {
            overlay: true,  
            baseClass: 'k-offcanvas-panel',
            closeBy: 'k_offcanvas_toolbar_search_close',
            toggleBy: 'k_offcanvas_toolbar_search_toggler_btn'
        }); 

        KUtil.scrollInit(body, {
            disableForMobile: true, 
            resetHeightOnDestroy: true, 
            handleWindowResize: true, 
            height: function() {
                var height = parseInt(KUtil.getViewPort().height);
               
                if (head) {
                    height = height - parseInt(KUtil.actualHeight(head));
                    height = height - parseInt(KUtil.css(head, 'marginBottom'));
                }
        
                height = height - parseInt(KUtil.css(searchPanel, 'paddingTop'));
                height = height - parseInt(KUtil.css(searchPanel, 'paddingBottom'));    

                return height;
            }
        });
    }

    return {     
        init: function() {  
            initNotifications(); 
            initQucikActions();
            initProfile();
            initSearch();
        }
    };
}();

$(document).ready(function() {
    KOffcanvasPanel.init();
});
var KQuickPanel = function() {
    var panel = KUtil.get('k_quick_panel');
    var notificationPanel = KUtil.get('k_quick_panel_tab_notifications');
    var actionsPanel = KUtil.get('k_quick_panel_tab_actions');
    var settingsPanel = KUtil.get('k_quick_panel_tab_settings');

    var getContentHeight = function() {
        var height;
        var nav = KUtil.find(panel, '.k-quick-panel__nav');
        var content = KUtil.find(panel, '.k-quick-panel__content');

        height = parseInt(KUtil.getViewPort().height) - parseInt(KUtil.actualHeight(nav)) - (2 * parseInt(KUtil.css(nav, 'padding-top'))) - 10;

        return height;
    }

    var initOffcanvas = function() {
        var offcanvas = new KOffcanvas(panel, {
            overlay: true,  
            baseClass: 'k-quick-panel',
            closeBy: 'k_quick_panel_close_btn',
            toggleBy: 'k_quick_panel_toggler_btn'
        });   
    }

    var initNotifications = function() {
        KUtil.scrollInit(notificationPanel, {
            disableForMobile: true, 
            resetHeightOnDestroy: true, 
            handleWindowResize: true, 
            height: function() {
                return getContentHeight();
            }
        });
    }

    var initActions = function() {
        KUtil.scrollInit(actionsPanel, {
            disableForMobile: true, 
            resetHeightOnDestroy: true, 
            handleWindowResize: true, 
            height: function() {
                return getContentHeight();
            }
        });
    }

    var initSettings = function() {
        KUtil.scrollInit(settingsPanel, {
            disableForMobile: true, 
            resetHeightOnDestroy: true, 
            handleWindowResize: true, 
            height: function() {
                return getContentHeight();
            }
        });
    }

    var updatePerfectScrollbars = function() {
        $(panel).find('a[data-toggle="tab"]').on('shown.bs.tab', function (e) { 
            KUtil.scrollUpdate(notificationPanel);
            KUtil.scrollUpdate(actionsPanel);
            KUtil.scrollUpdate(settingsPanel);
        });
    }

    return {     
        init: function() {  
            initOffcanvas(); 
            initNotifications();
            initActions();
            initSettings();
            updatePerfectScrollbars();
        }
    };
}();

$(document).ready(function() {
    KQuickPanel.init();
});